//
//  DatePickerView.swift
//  SwiftProject
//
//  Created by qindong on 2021/4/1.
//

import UIKit

class DatePickerView: UIView {
    let datePickView = UIDatePicker()
    
    var selectBlock : ((_ date : String?)->Void)?
    
    var currectDay : String! {
        didSet {
            if let date = currectDay.toDate()?.date {
                if date.compare(Date()) == .orderedDescending {
                    datePickView.date = Date()
                } else {
                    datePickView.date = date
                }
            }
        }
    }
    
    init() {
        super.init(frame: .zero)
    }
    
    private override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 229))

        backgroundColor = .white
        
        let sureBtn = QMUIButton()
        sureBtn.setTitle("确定", for: .normal)
        sureBtn.setTitleColor(.colorMain, for: .normal)
        sureBtn.titleLabel?.font = .systemFont(ofSize: 18)
        sureBtn.tag = 1
        sureBtn.addTarget(self, action: #selector(buttonClick(_:)), for: .touchUpInside)
        addSubview(sureBtn)
        
        sureBtn.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: 62, height: 42))
            make.right.top.equalTo(0)
        }
        
        let cancalBtn = QMUIButton()
        cancalBtn.setTitle("取消", for: .normal)
        cancalBtn.setTitleColor(.colorMake(153, 153, 153), for: .normal)
        cancalBtn.titleLabel?.font = .systemFont(ofSize: 18)
        cancalBtn.tag = 2
        cancalBtn.addTarget(self, action: #selector(buttonClick(_:)), for: .touchUpInside)
        addSubview(cancalBtn)
        
        cancalBtn.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: 62, height: 42))
            make.left.top.equalTo(0)
        }
        
        datePickView.backgroundColor = .white
        datePickView.datePickerMode = .date
        if #available(iOS 14, *) {
            datePickView.preferredDatePickerStyle = .wheels
            datePickView.locale = Locale(identifier: "zh_CN")
        }
        datePickView.minimumDate = Date(timeIntervalSince1970: -2209017600)
        datePickView.maximumDate = Date()
        addSubview(datePickView)
        
        datePickView.snp.makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.top.equalTo(42)
            make.height.equalTo(187)
        }
    }
    
    @objc func buttonClick(_ sender : QMUIButton) {
        if sender.tag == 1 {
            if selectBlock != nil {
                let formatter : DateFormatter = DateManager.shared.formatter
                formatter.dateFormat = "yyyy-MM-dd"
                selectBlock!(formatter.string(from: datePickView.date))
            }
        } else {
            selectBlock!(nil)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
